package com.xq.sboot.controller;

import com.xq.sboot.domain.User;
import com.xq.sboot.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 功能说明: 用户控制器类.
 * <p>创建时间:2018-12-09 21:48</p>
 * @author <a href="https://gitee.com/gkq/microservice">郭凯强</a>
 * @since 1.0.0
 */
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserRepository userRepository;

    /**
     * 获取用户列表
     * @return 用户列表
     */
    @GetMapping
    public List<User> getUsers(){
        return this.userRepository.listUser();
    }

    /**
     * 获取用户信息
     * @param id 用户ID
     * @return 用户ID对应的实体对象
     */
    @GetMapping("/{id}")
    public User getUser(@PathVariable("id") Long id){
        return this.userRepository.getUserById(id);
    }

    /**
     * 创建用户
     * @param user 要创建的用户
     * @return 创建后的用户
     */
    @PostMapping
    @PreAuthorize("hasPermission('admin')")
    public User createUser(@RequestBody User user) {
        return this.userRepository.saveOrUpdateUser(user);
    }

    /**
     * 修改用户
     * @param id 用户ID
     * @param user 要修改的用户
     */
    @PutMapping("/{id}")
    public void updateUser(@PathVariable("id") Long id,@RequestBody User user){
        User oldUser = this.userRepository.getUserById(id);
        if (null != oldUser) {
            user.setId(id);
            this.userRepository.saveOrUpdateUser(user);
        }
    }

    /**
     * 删除用户
     * @param id 用户ID
     */
    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable("id") Long id) {
        this.userRepository.deleteUser(id);
    }
}
